#include "component/Doodle.h"
#include <iostream>

using namespace eats_core;

Doodle::Doodle(std::string file, SDL_Surface * _surf_dest, int * _posX = 0, int * _posY = 0, bool _relative = false)
{
	if ( !file.empty() ) {
		_file = file;
	} else {
		_file = "assets/test_img.bmp";
	}

	surf_dest = _surf_dest;

	posX = _posX;
	posY = _posY;

	relative = _relative;
}

Doodle::~Doodle()
{
    //dtor
}

bool Doodle::setUp()
{
	if(surf_dest == NULL) {
		std::cout << "|ERROR| Não foi possível definir a superficie de destino." << std::endl;
		return false;
	}

	std::cout << "|INFO| Carregando imagem de : " << _file << std::endl;
    _doodle_img = loadIMG(_file);

    if(_doodle_img == NULL ) {
    	std::cout << "|ERROR| Não foi possível carregar a image ["<< _file << "]" << std::endl;
    	return false;
    }
    std::cout << "|INFO| Imagem ["<< _file << "] carregada com sucesso" <<  std::endl;

	if(relative) {
		*posX -= _doodle_img->w /2;
		*posY -= _doodle_img->h /2;
	}

    return true;
}

bool Doodle::tearDown()
{
    SDL_FreeSurface(_doodle_img);
    return true;
}

bool Doodle::render()
{
    return drawIMG(surf_dest , _doodle_img, * posX, * posY);
}

bool Doodle::render(int x, int y, int w, int h)
{
	return drawIMG(surf_dest , _doodle_img,* posX,* posY, x, y, w, h);
}

bool Doodle::render(int x, int y, int x2 , int y2, int w, int h)
{
	return drawIMG(surf_dest , _doodle_img, x, y, x2, y2, w, h);
}

SDL_Surface* Doodle::loadIMG(std::string file)
{
    SDL_Surface* Surf_Temp = NULL;
    SDL_Surface* Surf_Return = NULL;


    if( (Surf_Temp = IMG_Load(file.c_str()) ) == NULL) {
    	std::cout << "|ERROR| " <<  IMG_GetError() << std::endl;
        return NULL;
    }

    Surf_Return = SDL_DisplayFormatAlpha(Surf_Temp);

    SDL_FreeSurface(Surf_Temp);

    return Surf_Return;
}

bool Doodle::drawIMG(SDL_Surface* Surf_Dest, SDL_Surface* Surf_Src, int X, int Y) {
    if(Surf_Dest == NULL || Surf_Src == NULL) {
        return false;
    }

    SDL_Rect DestR;

    DestR.x = X;
    DestR.y = Y;

    if ( SDL_BlitSurface(Surf_Src, NULL, Surf_Dest, &DestR) != 0 )
    	return false;

    return true;
}

bool Doodle::drawIMG(SDL_Surface* Surf_Dest, SDL_Surface* Surf_Src, int X, int Y, int X2, int Y2, int W, int H) {
    if(Surf_Dest == NULL || Surf_Src == NULL) {
        return false;
    }

    SDL_Rect DestR;

    DestR.x = X;
    DestR.y = Y;

    SDL_Rect SrcR;

    SrcR.x = X2;
    SrcR.y = Y2;
    SrcR.w = W;
    SrcR.h = H;

    if ( SDL_BlitSurface(Surf_Src, &SrcR, Surf_Dest, &DestR)!= 0 )
    	return false;

    return true;
}
